<template>
  <div class="authority">
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addAuthority">新增角色</el-button>
      </div>
      <div class="ant-alert-info">
        <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
          <div class="pop-content">
            <div class="pop-title">自定义列</div>
            <div class="check-list">
              <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <template #reference>
            <div class="anticon">
              <el-icon size="16" color="#1890ff">
                <Setting />
              </el-icon>
              <div style="margin-left: 2px;">自定义列</div>
            </div>
          </template>
        </el-popover>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column align="left" label="角色名" prop="name" v-if="checkedColumns.includes('角色名')"></el-table-column>
        <el-table-column align="left" label="角色标识" prop="roleCode"
          v-if="checkedColumns.includes('角色标识')"></el-table-column>
        <el-table-column align="left" label="所属系统" v-if="checkedColumns.includes('所属系统')">
          <template #default="scope">
            <span>{{ scope.row.front == 1 ? '客户端' : '管理端' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column align="left" label="创建时间" prop="createdAt"></el-table-column> -->
        <!-- <el-table-column align="left" label="排序" min-width="70" prop="sort" /> -->
        <el-table-column align="left" fixed="right" label="操作" min-width="160" v-if="checkedColumns.includes('操作')">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="editRole(scope.row.id)">
              编辑
            </el-button>
            <el-button type="danger" link icon="delete" @click="deleteRole(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="appStore.drawerSize" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog"> 取 消 </el-button>
            <el-button type="primary" @click="enterDialog"> 确 定 </el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" :model="form" ref="authorityForm" label-width="120" :rules="rules">
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="角色名" prop="name">
              <el-input v-model="form.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色标识" prop="roleCode">
              <el-input v-model="form.roleCode" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="所属系统">
              <el-radio-group v-model="form.front">
                <el-radio :value="1" size="large">客户端</el-radio>
                <el-radio :value="2" size="large">管理端</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色描述">
              <el-input v-model="form.roleDesc" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full" style="margin-top: 20px;">
          <el-col :span="12">
            <!-- <div>菜单权限</div> -->
            <el-tree ref="menuTree" :data="menuList" :default-checked-keys="menuTreeIds" default-expand-all
              show-checkbox node-key="id" :props="defaultProps" @check="nodeChange" />
          </el-col>
          <!-- <el-col :span="12" v-if="form.dataScope == 2">
            <el-tree ref="departTree" :data="departList" :default-checked-keys="departTreeIds" default-expand-all
              show-checkbox node-key="id" :props="departProps" @check="departChange" />
          </el-col> -->
        </el-row>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  getMenuList
} from '@/api/menu'
import {
  getDepartTree
} from '@/api/depart'
import {
  getAuthorityList,
  deleteAuthority,
  createAuthority,
  updateAuthority,
  authorityInfo
} from '@/api/authority'
import { reactive, ref, onMounted, computed } from 'vue'
import { useAppStore } from "@/pinia";
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouterStore } from '@/pinia/modules/router'
import router from '@/router'

defineOptions({
  name: 'Authority'
})
const appStore = useAppStore()
const options = [
  {
    value: 1,
    label: '全部',
  },
  {
    value: 2,
    label: '自定义',
  },
  {
    value: 3,
    label: '本部门',
  },
  {
    value: 4,
    label: '本部门及以下',
  },
  {
    value: 5,
    label: '本人',
  }
]

const rules = reactive({
  name: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
  roleCode: [{ required: true, message: '请输入角色标识', trigger: 'blur' }],
})
const checkedColumns = ref(['角色名', '角色标识', '所属系统', '操作'])
if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).authority) {
  checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).authority
}
const columns = ref(['角色名', '角色标识', '所属系统', '操作'])
const handleColumnsChange = (val) => {
  let obj = {
    
  }
  if (localStorage.getItem('columnData')) {
    obj = JSON.parse(localStorage.getItem('columnData'))
  }
  obj.authority=val
  localStorage.setItem('columnData', JSON.stringify(obj))
}
const form = ref({
  front: 1,
  departIds: [],
  menuIds: [],
  name: '',
  roleDesc: ''
})
const dialogFormVisible = ref(false)
const defaultProps = {
  children: 'children',
  label: 'title'
}

const authorityForm = ref(null)
const initForm = () => {
  authorityForm.value.resetFields()
  form.value = {
    front: 1,
    departIds: [],
    menuIds: [],
    name: '',
    roleDesc: ''
  }
}
const isEdit = ref(false)
const dialogTitle = ref('新增角色')
const addAuthority = () => {
  getMenuData()
  dialogTitle.value = '新增角色'
  isEdit.value = false
  dialogFormVisible.value = true
}

const getMenuData = () => {
  getMenuList().then(res => {
    allMenuList.value = res.result
    allMenuList.value.forEach(item => {
      item.title = item.meta.title
      if (item.children && item.children.length > 0) {
        item.children.forEach(m => {
          m.title = m.meta.title
          if (m.children && m.children.length > 0) {
            m.children.forEach(n => {
              n.title = n.meta.title
            })
          }
        })
      }
    })
  })
}

const handleClose = (done) => {
  initForm()
  done()
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}
const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await getAuthorityList()
  if (res.code == 200) {
    tableData.value = res.result
  }
}
getTableData()

const allMenuList = ref([])
const menuList = computed(() => {
  return allMenuList.value.filter(item => item.system == form.value.front)
})
onMounted(() => {

})

const radioChange = (val) => {
  menuList.value = allMenuList.value.filter(item => item.system == val)
}

const menuTree = ref(null)
const menuTreeIds = ref([])
const nodeChange = (m, n) => {

}

const enterDialog = async () => {
  authorityForm.value.validate(async (valid) => {
    if (valid) {
      let arr = menuTree.value.getCheckedNodes(false, true)
      if (arr.length > 0) {
        form.value.menuIds = arr.map(item => item.id)
      }
      let res
      if (isEdit.value) {
        res = await updateAuthority(form.value)
      } else {
        res = await createAuthority(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
        //await getRouter()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}
const getRouter = async () => {
  const routerStore = useRouterStore()
  await routerStore.SetAsyncRouter()
  const asyncRouters = routerStore.asyncRouters
  asyncRouters.forEach((asyncRouter) => {
    router.addRoute(asyncRouter)
  })
}
const deleteRole = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteAuthority(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const departCheckedKeys = ref([])
const menuCheckedKeys = ref([])

const editRole = async (id) => {
  isEdit.value = true
  dialogTitle.value = '编辑角色'
  getMenuData()
  authorityInfo(id).then(res => {
    form.value = res.result
    const { departIds, menuIds } = res.result
    menuTreeIds.value = getArr(menuIds)
    if (departIds.length > 0) {
      form.value.departIds = departIds.map(item => item.id)
    }
    if (menuIds.length > 0) {
      form.value.menuIds = menuIds.map(item => item.id)
    }
    //const arr = []
    // menus.forEach((item) => {
    //   // 防止直接选中父级造成全选
    //   if (!menus.some((same) => same.parentId === item.id)) {
    //     arr.push(Number(item.id))
    //   }
    // })
    // menuTreeIds.value = arr

    form.value.roleId = Number(id)
  })
  dialogFormVisible.value = true
}

const getArr = (arr) => {
  const res = []
  arr.forEach((item) => {
    // 防止直接选中父级造成全选
    if (!arr.some((same) => same.parentId === item.id)) {
      res.push(Number(item.id))
    }
  })
  return res
}
</script>

<style lang="scss">
.ant-alert-info {
  display: flex;
  justify-content: end;
  align-items: center;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
  padding: 5px;

  .anticon {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

.pop-content {
  .pop-title {
    font-weight: bold;
    padding-bottom: 4px;
    border-bottom: 1px solid rgba(5, 5, 5, 0.06);
  }

  .el-checkbox-group {
    font-size: 0;
    line-height: 0;
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
